package com.able.concurrency.t5;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 * @author abel.he
 * @data 2018/10/29 18:39
 * @describe
 *  练习：
 * 启动若干线程，并行访问同一个容器中的数据。保证获取容器中数据时没有数据错误，且线程安全。
 * 如：售票，秒杀等业务。
 */
public class Test92_concurrency {

    static List<String> list = new ArrayList<>();
//    static List<String> list = new Vector<>();

    static {
        for (int i = 0; i < 1000; i++) {
            list.add("value" + i);
        }
    }

    public static void main(String[] args) {
        /*for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
//                    while (true) {
//                        if (list.size() > 0) {
//                            System.out.println(Thread.currentThread().getName() + " - " + list.remove(0));
//                        }
//                    }
                    while(list.size() > 0){
                        System.out.println(Thread.currentThread().getName() + " - " + list.remove(0));
                    }
                }
            }, "thread" + i).start();
        }*/

        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        synchronized (list) {
                            if (list.size() > 0) {
                                System.out.println(Thread.currentThread().getName() + " - " + list.remove(0));
                            }
                        }
                    }
                }
            }, "thread" + i).start();
        }

    }

}
